
	import draggable from "vuedraggable";
	import UploadAudio from "../uploadAudio.vue";
	import EditorDialog from "@rc/pages/components/question-base/editor-dialog.vue";
	// 单选 不定项选择，多项选择
    let questionComponents = {
        QChoiceEdit: () => import("@rc/pages/components/question-base/q-choice/edit.vue"),
        QCompatibilityEdit: () => import("@rc/pages/components/question-base/q-compatibility/edit.vue"),
        QJudgeEdit: () => import("@rc/pages/components/question-base/q-judge/edit.vue"),
        QListeningEdit: () => import("@rc/pages/components/question-base/q-listening/edit.vue"),
        QBlankEdit: () => import("@rc/pages/components/question-base/q-blank/edit.vue"),
        QShortAnswer: () => import("@rc/pages/components/question-base/q-short-answer/edit.vue"),
        QChooseWord: () => import("@rc/pages/components/question-base/q-choose-word/edit.vue"),
        QCaseAnalysis: () => import("@rc/pages/components/question-base/q-case-analysis/edit.vue"),
    };
	export default {
        inheritAttrs: true,
		components: {
			draggable,
			UploadAudio,
			EditorDialog
		},
		props: {
			parentType: {
				//编辑子题时,大题类型
				type: String,
				default: ""
			},
			initData: {
				type: Object,
				default: () => {}
			},
			basicInfo: {
				type: Object,
				default: () => {}
			},
			tagInfo: {
				type: Object,
				default: () => {}
			},
            type:{//编辑或者新增
                type: String,
				default: ""
            }
		},
		data() {
			return {
				editInfo: {
					editValue: "",
					key: ""
				},
				isShowEdit: false,
				questionForm: {
                    optionList:[]
                }, // 试题信息
				questionInfo: {}, // 用于试题组件初始化数据
				questionTypes: {}, // 题型数据来源
				isShowProcess: false,
				tempFile: {
					name: "",
					percent: 0
				},
				combinedType: ["A", "CF", "L", "C"], //组合题型
				labelWidth: "80px"
			};
		},
        computed:{
            //题型对应的编辑组件
            qComponent(){
                const questionType = this.questionForm.questionType;
                //单选多选不定项选择
                if(['S','M','I'].includes(questionType)){
                    return questionComponents.QChoiceEdit;
                }
                // 配伍题
                if(questionType==='C'){
                    return questionComponents.QCompatibilityEdit;
                }
                // 判断题
                if(questionType==='J'){
                    return questionComponents.QJudgeEdit;
                }
                //听力题
                if(questionType==='L'){
                    return questionComponents.QListeningEdit;
                }
                 //填空题
                if(questionType==='F'){
                    return questionComponents.QBlankEdit;
                }
                //简答题
                if(questionType==='O'){
                    return questionComponents.QShortAnswer;
                }
                //选词填空题
                if(questionType==='BC'){
                    return questionComponents.QChooseWord;
                }
                // 案例分析 /完型填空
                if(['A','CF'].includes(questionType)){
                    return questionComponents.QCaseAnalysis;
                }
                return '';
            },
            //是否可以上传音频
            disabledUploadAudio(){
                return this.tempFile.percent;
            }
        },
		watch: {
			parentType: {
				immediate: true,
				deep: true,
				handler(val) {
					if (val === "A") {//案例分析
                        this.questionTypes = nlapp.Dictionary.get("question_a_subType");
					} else if (val === "CF") {//完型填空
                        this.questionTypes = nlapp.Dictionary.get("question_cf_subType");
					} else if (val === "L") {//听力题
                        this.questionTypes = nlapp.Dictionary.get("question_l_subType");
					} else if (val === "C") {//配伍题
                        this.questionTypes = nlapp.Dictionary.get("question_c_subType");
					} else {
						this.questionTypes = nlapp.Dictionary.get("rc_questionType");
					}
				}
			},
			initData: {
				immediate: true,
				deep: true,
				handler(initData) {
					if (initData) {
                        // 全部试题信息
						this.questionForm = JSON.parse(JSON.stringify(initData));
                        // 向组件初始化数据
						this.questionInfo = JSON.parse(JSON.stringify(initData));
                        //删除试题编辑组件之外的 解析/音频解析/视频解析
                        delete this.questionInfo.questionAnswerParse;
                        delete this.questionInfo.questionVideoPathList;
                        delete this.questionInfo.questionAudioPathList;
                        this.initPathList();
					}
				}
			},
			"questionForm.questionType": {
                immediate:true,
				handler(val) {
                    this.labelWidth = val === "O"?'120px':'80px';
					if (this.type==='add') {
						this.$nextTick(() => {
							this.$refs.questionFormRef.clearValidate();
						});
						const { questionTitle,optionList} = this.questionForm;
                        // 切换题型时，重置表单项
                        let question = {
							questionTitle,
							questionType: val,
                            optionList:[]
						};
                        //案例分析和完型填空和听力题
                        if(['A','CF','L'].includes(question.questionType)){
                            delete question.optionList;
                        } else {
                            question.optionList = [];
                        }
                        // 小题的大题是配伍题
                        if(this.parentType==='C') {
                            optionList.forEach((option)=>{
                                option.isAnswer='N';
                            });
                            question.optionList = optionList;
                        }
                        //清除答案
                        if(this.combinedType.includes(val)){
                            delete question.answer;
                            delete question.questionAnswerParse;
                        }
                        //删除智能阅卷关键词/关键词得分权重/听力音频/音频标识
                        delete this.questionForm.questionKeywords;
                        delete this.questionForm.questionScoreWeight;
                        delete this.questionForm.listeningAudioUrl;
                        delete this.questionForm.audioId;

                        this.questionInfo = question;
					}
                    this.initPathList();
				}
			},
			questionForm: {
				immediate: true,
				deep: true,
				handler(val) {
					this.$emit("change", val);
				}
			}
		},
		methods: {
            questionChange(val){
                this.questionForm = {
                    ...this.questionForm,
                    ...JSON.parse(JSON.stringify(val))
                };
            },
			/**文本框内变价 */
			handleEdit(content, key, index) {
				this.isShowEdit = true;
				this.editInfo = {
					editValue: content,
					key,
					index
				};
			},
            // 只保留br和图片信息
			getString(html) {
				// 把当前编辑器内容以行(p标签)的方式格式化成字符串列表
                let $html = $(`<div>${html}</div>`);;
				let content = '';
				$html.each(function() {
					let str = String($(this).html()); // 把每个p标签中的内容变成字符串
                    str = str.replace(/(\n)/gm, "<br>");
                    str = str.replace(/<(?!(img|br)).*?>/gm, ""); // 去除其他标签信息，只保留img标签 // 去除其他标签信息，只保留img标签
                    content+= str;
				});
				return content;
			},

			onEditorSuccess(html) {
                const {questionType} = this.questionForm;
                let message = '';
                html = this.getString(html);
				if (this.editInfo.key === "optionList") {
                    if(['S','M','I','C'].includes(questionType) && html.length>500){
                        message = "选项最大输入500字";
                    }
                    if(questionType==='O' && html.length>2000){
                        message = '答案最大输入2000字';
                    }
                    if(['BC','F'].includes(questionType)&& html.length>100){
                        const name = questionType==='F'?'答案':'选项';
                        message = name+"选项最大输入100字";
                    }
                    if(message){
                        this.$message.warning(message);
                        return;
                    }
                    this.questionForm.optionList[this.editInfo.index].answerOption = html;
				} else {
                    if(this.editInfo.key==='questionTitle' && html.length>2000){
                        const name = questionType==='A'?'背景材料':'题干';
                        message = name+"最大输入2000字";
                    }
                    if(this.editInfo.key==='questionAnswerParse' && html.length>2000){
                        message = "解析最大输入2000字";
                    }
                    if(message){
                        this.$message.warning(message);
                        return;
                    }
                    this.questionForm[this.editInfo.key] = html;
                }
                this.isShowEdit = false;
                //解析内容
                if(this.editInfo.key !=='questionAnswerParse'){
                    if(this.editInfo.key === "optionList") {
                        this.$set( this.$refs.questionRef.questionForm,'optionList',JSON.parse(JSON.stringify(this.questionForm.optionList)));
                    } else {
                       this.$set( this.$refs.questionRef.questionForm,this.editInfo.key,html);
                    }
                }
			},
			addVideoList() {
				let length = this.questionForm.questionVideoPathList.length;
				if (length >= 3) {
					this.$message.warning("最多可添加3条解析");
					return;
				}
				this.questionForm.questionVideoPathList.push({
					key: Date.now(),
					questionAvPath: "",
					questionAvSeq: length + 1
				});
			},
			deleteVideoList(index) {
				this.questionForm.questionVideoPathList.splice(index, 1);
				this.questionForm.questionVideoPathList.forEach((item, index) => {
					item.questionAvSeq = index + 1;
				});
			},
            //视频排序后重置序号
            videoSortEnd(){
                this.questionForm.questionVideoPathList.forEach((item, index) => {
					item.questionAvSeq = index + 1;
				});
            },
            //音频排序后重置序号
            audioSortEnd(){
                this.questionForm.questionAudioPathList.forEach((item, index) => {
					item.questionAvSeq = index + 1;
				});
            },
			//音频
            onClickUploadAudio(){
                if(this.tempFile.percent){
                    this.$message.warning("音频上传中,请等待");
					return;
                }
            },
			addAudioList() {
				let length = this.questionForm.questionAudioPathList.length;
				if (length >= 3) {
					this.$message.warning("最多可添加3条解析");
					return;
				}
				this.questionForm.questionAudioPathList.push({
					questionAvPath:"",
					key: Date.now(),
					questionAvSeq: length + 1
				});
			},
			deleteAudioList(index) {
                if(this.tempFile.percent){
                    this.$message.warning("音频上传中不能删除");
					return;
                }
				this.questionForm.questionAudioPathList.splice(index, 1);
				this.questionForm.questionAudioPathList.forEach((item, index) => {
					item.questionAvSeq = index + 1;
				});
			},
			vidUploadSuccess(file,index) {
				this.tempFile = {};
				this.isShowProcess = false;
                //清除上传的文件
				this.$refs['uploadAudioRef'+index][0].reset();
                let audio = this.questionForm.questionAudioPathList[index];
                audio.questionAvPath = file.filePath;
                this.$set(this.questionForm.questionAudioPathList,index,audio);
			},
			vidProgress({ file }) {
				this.isShowProcess = true;
				this.videoFlag = true;
				this.tempFile = {
					name: file.name,
					percent: file.percentage.toFixed(0)
				};
			},
            //初始化音视频列表
            initPathList(){
                const {questionVideoPathList,questionAudioPathList,questionType} = this.questionForm;
                if (!this.combinedType.includes(questionType)) {

                    if(!questionVideoPathList || questionVideoPathList.length===0){
                        this.$set(this.questionForm, "questionVideoPathList", [
                            {
                                key: Date.now(),
                                questionAvPath: "",
                                questionAvSeq: 1
                            }
                        ]);
                    }
                    if(!questionAudioPathList || questionAudioPathList.length===0){
                        this.$set(this.questionForm, "questionAudioPathList", [
                            {
                                key: Date.now(),
                                questionAvPath: "",
                                questionAvSeq: 1
                            }
                        ]);
                    }
                }
            },
            api_validate(){
               return this.$refs.questionFormRef.validate().then(()=>{
                   //校验必填项之外的其他信息
                   let  questionValidate = true;
                   if(this.$refs.questionRef.api_checkAnswer) {
                    questionValidate = this.$refs.questionRef.api_checkAnswer();
                   }
                   const {questionAudioPathList,questionType} = this.questionForm;
                    if (!this.combinedType.includes(questionType)){//音频后缀
                        if(!questionValidate){
                            return false;
                        }
                        const audioFormatError = questionAudioPathList.some(audio=>audio.questionAvPath && !(/.mp3$/.test(audio.questionAvPath)));
                        if(audioFormatError){
                            this.$message.warning("请检查音频解析格式是否为mp3文件");
					        return false;
                        } else {
                            return true;
                        }
                    } else {
                        return questionValidate;
                    }
               }).catch(data=>{
                 return data;
               });
            }
		}
	};
